import React from 'react';
import {Table} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {Link} from 'react-router-dom';
import {PAGINATION_OPTIONS, TABLE, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT, DATE_FORMAT, FIXED_COLUMN_WIDTH} from '../constants';
import {PERMISSION, formatPrintPdfUrl} from './constants';
import {injectIntl} from './intl';
import {conventEnumValueToString, formatDateTime, formatAmount, exportDownload} from '../utils';
import {hasPermissions} from './utils';
import {paymentType, partOrderPriceTerms, transportType, currency, proformaInvoiceStatus} from '../Enum';
import {abandonData, cancelData, getPiExcel} from './api';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import DropdownMenu from 'Shared/components/DropdownMenu';
const basePath = fetch.basePath || '';
const url = '/#/dcs/parts/stockRequirement/add';
export class TablePanel extends React.PureComponent {
    constructor(props) {
        super(props);
        this.onChangeSort = this.onChangeSort.bind(this);
        this.state = {
            loading: false
        };
    }

    onChangeSort = (pagination, filters, sorter) => {
        this.props.onChangeSort({
            pageIndex: pagination.current - 1,
            pageSize: pagination.pageSize,
            sortedColumnKey: sorter.columnKey,
            sortedOrder: sorter.order,
        });
    };
    onClickAbandonBtn = id => {
        this.setState({loading: true});
        const record = this.props.list.find(d => d.id === id);
        abandonData(id, {rowVersion: record.rowVersion})
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.refreshListData();
            });
    }
    onClickCancelBtn = id => {
        this.setState({loading: true});
        const record = this.props.list.find(d => d.id === id);
        cancelData(id, {rowVersion: record.rowVersion})
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.refreshListData();
            });
    }
    onExportExcel = id => {
        this.setState({
            loading: true
        });
        getPiExcel(id).then(res => {
            this.setState({
                loading: false
            });
            exportDownload(res);
        });
    }
    onPrintPdf = e => {
        e.stopPropagation();
        window.open(formatPrintPdfUrl(e.currentTarget.dataset.id, e.currentTarget.dataset.code));
    }
    render() {
        const colums = [
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.code',
                    defaultMessage: 'PI编号'
                }),
                dataIndex: 'code',
                width: '100px',
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'code' && this.props.sortedOrder,
                render: (text, record) => <Link to={routes.detail.format(record.id)} >{text}</Link>
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.partOrderCode',
                    defaultMessage: '备件订单编号'
                }),
                dataIndex: 'partOrderCode',
                width: '100px',
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'partOrderCode' && this.props.sortedOrder
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.status',
                    defaultMessage: 'PI状态'
                }),
                dataIndex: 'status',
                sortOrder: this.props.sortedColumnKey === 'status' && this.props.sortedOrder,
                render: text => conventEnumValueToString(proformaInvoiceStatus, text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.brandCode',
                    defaultMessage: '品牌编号'
                }),
                dataIndex: 'brandCode'
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.customerOrderCode',
                    defaultMessage: '客户订单号'
                }),
                dataIndex: 'customerOrderCode',
                sortOrder: this.props.sortedColumnKey === 'customerOrderCode' && this.props.sortedOrder,
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.partOrderTypeName',
                    defaultMessage: '订单类型'
                }),
                dataIndex: 'partOrderTypeName'
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.partOrderPriceTerms',
                    defaultMessage: '价格条款'
                }),
                dataIndex: 'partOrderPriceTerms',
                sortOrder: this.props.sortedColumnKey === 'partOrderPriceTerms' && this.props.sortedOrder,
                render: text => conventEnumValueToString(partOrderPriceTerms, text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.paymentType',
                    defaultMessage: '付款方式'
                }),
                dataIndex: 'paymentType',
                sortOrder: this.props.sortedColumnKey === 'paymentType' && this.props.sortedOrder,
                render: text => conventEnumValueToString(paymentType, text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.transportType',
                    defaultMessage: '运输方式'
                }),
                dataIndex: 'transportType',
                sortOrder: this.props.sortedColumnKey === 'transportType' && this.props.sortedOrder,
                render: text => conventEnumValueToString(transportType, text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.totalQuantity',
                    defaultMessage: '订购数量'
                }),
                dataIndex: 'totalQuantity',
                sortOrder: this.props.sortedColumnKey === 'totalQuantity' && this.props.sortedOrder,
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.totalAmount',
                    defaultMessage: '订单总金额'
                }),
                dataIndex: 'totalAmount',
                sortOrder: this.props.sortedColumnKey === 'totalAmount' && this.props.sortedOrder,
                render: text => formatAmount(text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.piAmount',
                    defaultMessage: 'PI金额'
                }),
                dataIndex: 'piAmount',
                render: text => formatAmount(text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.shipmentAmount',
                    defaultMessage: '运费'
                }),
                dataIndex: 'shipmentAmount',
                render: text => formatAmount(text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.insuranceAmount',
                    defaultMessage: '保费'
                }),
                dataIndex: 'insuranceAmount',
                render: text => formatAmount(text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.currency',
                    defaultMessage: '币种'
                }),
                dataIndex: 'currency',
                render: text => conventEnumValueToString(currency, text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.submitTime',
                    defaultMessage: '提报日期'
                }),
                dataIndex: 'submitTime',
                render: text => formatDateTime(text, DATE_FORMAT)
            }];
        if(!this.props.isDealerUser)
            colums.splice(1, 0, ...[
                {
                    title: this.props.intl.formatMessage({
                        id: 'tablePanel.column.dealerCode',
                        defaultMessage: '总代编号'
                    }),
                    dataIndex: 'dealerCode'
                }
            ]);
        colums.push({
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.operation',
                defaultMessage: '操作'
            }),
            dataIndex: 'id',
            key: 'id',
            width: FIXED_COLUMN_WIDTH,
            fixed: 'right',
            render: (text, r) => {
                const menus = [{
                    id: PERMISSION.update,
                    children: <Link key="update" to={routes.update.format(r.id)}>{
                        this.props.intl.formatMessage({
                            id: 'tablePanel.update',
                            defaultMessage: '编辑'
                        })
                    }</Link>,
                    hidden: !(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(r.options, PERMISSION.update)),
                }, {
                    id: PERMISSION.confirm,
                    children: <Link key="confirm" to={routes.confirm.format(r.id)}>{
                        this.props.intl.formatMessage({
                            id: 'tablePanel.confirm',
                            defaultMessage: '确认'
                        })
                    }</Link>,
                    hidden: !(hasPermissions(this.props.permissions, PERMISSION.confirm) && hasPermissions(r.options, PERMISSION.confirm)),
                }, {
                    id: PERMISSION.audit,
                    children: <Link key="audit" to={routes.audit.format(r.id)}>{
                        this.props.intl.formatMessage({
                            id: 'tablePanel.audit',
                            defaultMessage: '资金审核'
                        })
                    }</Link>,
                    hidden: !(hasPermissions(this.props.permissions, PERMISSION.audit) && hasPermissions(r.options, PERMISSION.audit)),
                }, {
                    id: PERMISSION.abandon,
                    children: (ref =>
                        <WrappedPopconfirm
                            key="abandon"
                            placement="topLeft"
                            onConfirm={this.onClickAbandonBtn}
                            id={r.id}
                            onVisibleChange={ref.setMenuVisible}
                            title={this.props.intl.formatMessage({
                                id: 'tablePanel.validate.abandon',
                                defaultMessage: '是否确认作废？'
                            })}>
                            <a>{
                                this.props.intl.formatMessage({
                                    id: 'tablePanel.abandon',
                                    defaultMessage: '作废'
                                })
                            }</a>
                        </WrappedPopconfirm>
                    ),
                    hidden: !(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(r.options, PERMISSION.abandon)),
                }, {
                    id: PERMISSION.cancel,
                    children: (ref =>
                        <WrappedPopconfirm
                            key="cancel"
                            placement="topLeft"
                            onConfirm={this.onClickCancelBtn}
                            id={r.id}
                            onVisibleChange={ref.setMenuVisible}
                            title={this.props.intl.formatMessage({
                                id: 'tablePanel.validate.cancel',
                                defaultMessage: '是否确认取消订单'
                            })}>
                            <a>{
                                this.props.intl.formatMessage({
                                    id: 'tablePanel.cancel',
                                    defaultMessage: '取消'
                                })
                            }</a>
                        </WrappedPopconfirm>
                    ),
                    hidden: !(hasPermissions(this.props.permissions, PERMISSION.cancel) && hasPermissions(r.options, PERMISSION.cancel)),
                }, {
                    id: PERMISSION.create,
                    children: <a href={`${basePath}${url}?partSaleOrderId=${r.partSaleOrderId}`} target="_blank" rel="noopener noreferrer">{
                        this.props.intl.formatMessage({
                            id: 'tablePanel.create',
                            defaultMessage: '生成备货需求'
                        })
                    }</a>,
                    hidden: !(hasPermissions(this.props.permissions, PERMISSION.create) && hasPermissions(r.options, PERMISSION.create)),
                }, {
                    id: PERMISSION.printExcel,
                    children: (ref =>
                        <WrappedPopconfirm
                            key="printExcel"
                            placement="topLeft"
                            onConfirm={this.onExportExcel}
                            onVisibleChange={ref.setMenuVisible}
                            id={r.id}
                            title={this.props.intl.formatMessage({
                                id: 'tablePanel.message.printExcel',
                                defaultMessage: '是否下载Excel？'
                            })}>
                            <a>{this.props.intl.formatMessage({
                                id: 'tablePanel.operation.printExcel',
                                defaultMessage: '下载Excel'
                            })}</a>
                        </WrappedPopconfirm>
                    ),
                    hidden: !(hasPermissions(this.props.permissions, PERMISSION.printExcel) && hasPermissions(r.options, PERMISSION.printExcel))
                }, {
                    id: PERMISSION.printPdf,
                    children: (
                        <a key="printPdf" data-id={r.id} data-code={r.partOrderCode} onClick={this.onPrintPdf}>
                            {this.props.intl.formatMessage({
                                id: 'tablePanel.operation.printPdf',
                                defaultMessage: '下载PDF'
                            })}
                        </a>
                    ),
                    hidden: !hasPermissions(this.props.permissions, PERMISSION.printPdf)
                }];
                return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
            }
        });
        const pagination = {
            total: this.props.total,
            pageSize: this.props.pageSize,
            current: this.props.pageIndex + 1,
            ...PAGINATION_OPTIONS
        };
        const locale = {
            emptyText: this.props.errorMessage ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        return (
            <div>
                <Table
                    className="white-space-nowrap"
                    columns={colums}
                    dataSource={this.props.list}
                    onChange={this.onChangeSort}
                    rowKey="id"
                    pagination={pagination}
                    loading={this.props.loading || this.state.loading}
                    locale={locale}
                    {...TABLE} />
            </div>
        );
    }
}

TablePanel.propTypes = {
    errorMessage: PropTypes.string.isRequired,
    list: PropTypes.array.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
    refreshListData: PropTypes.func,
    sortedColumnKey: PropTypes.string,
    sortedOrder: PropTypes.string,
};

import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {tableSearch} from './actions';

const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    isDealerUser: state.getIn((['page', 'domainData', 'initData', 'isDealerUser'])),
    list: getData(state),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    errorMessage: state.getIn(['page', 'domainData', 'list', 'message']),
    sortedColumnKey: state.getIn(['page', 'appState', 'queryBySort', 'sortedColumnKey']),
    sortedOrder: state.getIn(['page', 'appState', 'queryBySort', 'sortedOrder']),
    permissions: getPermissions(state),
});

const mapDispatchToProps = dispatch => ({
    onChangeSort: option => dispatch(tableSearch(option)),
    refreshListData: () => dispatch(tableSearch())
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanel));
